package com.gitee.linzl.zuul.gateway.fiters.post;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import com.gitee.linzl.zuul.gateway.fiters.AbstractJSONPostFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;

import lombok.extern.slf4j.Slf4j;

/**
 * 只打印JSON格式的返回结果
 * 
 * @description
 * @author linzl
 * @email 2225010489@qq.com
 * @date 2018年10月22日
 */
@Component
@Slf4j
public class JSONResponseFilter extends AbstractJSONPostFilter {
	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public Object run() throws ZuulException {
		if (log.isDebugEnabled()) {
			RequestContext ctx = RequestContext.getCurrentContext();
			HttpServletRequest request = ctx.getRequest();
			InputStream is = ctx.getResponseDataStream();
			String result = null;
			try {
				result = StreamUtils.copyToString(is, Charset.forName(request.getCharacterEncoding()));
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 可以修改返回body的内容 ,低版本要加上 ,不然body没了
			// ctx.setResponseBody(result);
			log.debug("响应数据结果:{}", result);
		}
		return null;
	}
}
